/**
 * 演示场景配置
 * 展示不同时间段和特殊情况下的医院数据变化
 */

import { realDataService } from './realData'

export interface DemoScenario {
  id: string
  name: string
  description: string
  timeOfDay: 'morning' | 'afternoon' | 'evening' | 'night'
  isWeekend: boolean
  specialEvents?: string[]
  dataModifiers: {
    patientFlowMultiplier: number
    alertSeverityIncrease: boolean
    equipmentIssues: boolean
    crowdingAreas: string[]
  }
}

export const demoScenarios: DemoScenario[] = [
  {
    id: 'morning_rush',
    name: '工作日早高峰',
    description: '工作日上午8-10点，门诊患者高峰期',
    timeOfDay: 'morning',
    isWeekend: false,
    specialEvents: ['体检高峰', '慢病复诊'],
    dataModifiers: {
      patientFlowMultiplier: 1.5,
      alertSeverityIncrease: true,
      equipmentIssues: false,
      crowdingAreas: ['急诊科', '内科', '挂号大厅']
    }
  },
  {
    id: 'afternoon_normal',
    name: '下午正常时段',
    description: '工作日下午2-4点，相对平稳期',
    timeOfDay: 'afternoon',
    isWeekend: false,
    dataModifiers: {
      patientFlowMultiplier: 1.0,
      alertSeverityIncrease: false,
      equipmentIssues: false,
      crowdingAreas: ['儿科', '外科']
    }
  },
  {
    id: 'evening_emergency',
    name: '晚间急诊高峰',
    description: '晚上7-9点，急诊科忙碌时段',
    timeOfDay: 'evening',
    isWeekend: false,
    specialEvents: ['下班时间意外伤害', '慢性病发作'],
    dataModifiers: {
      patientFlowMultiplier: 1.3,
      alertSeverityIncrease: true,
      equipmentIssues: false,
      crowdingAreas: ['急诊科', 'ICU']
    }
  },
  {
    id: 'night_quiet',
    name: '深夜值班',
    description: '夜间12-6点，医院最安静时段',
    timeOfDay: 'night',
    isWeekend: false,
    dataModifiers: {
      patientFlowMultiplier: 0.3,
      alertSeverityIncrease: false,
      equipmentIssues: true, // 夜间设备维护
      crowdingAreas: []
    }
  },
  {
    id: 'weekend_calm',
    name: '周末平静',
    description: '周末上午，相对较少的患者',
    timeOfDay: 'morning',
    isWeekend: true,
    dataModifiers: {
      patientFlowMultiplier: 0.7,
      alertSeverityIncrease: false,
      equipmentIssues: false,
      crowdingAreas: ['急诊科']
    }
  },
  {
    id: 'equipment_maintenance',
    name: '设备维护日',
    description: '计划设备维护，部分设备离线',
    timeOfDay: 'morning',
    isWeekend: false,
    specialEvents: ['CT维护', 'MRI校准', '手术室消毒'],
    dataModifiers: {
      patientFlowMultiplier: 0.8,
      alertSeverityIncrease: true,
      equipmentIssues: true,
      crowdingAreas: ['影像科等候区']
    }
  },
  {
    id: 'flu_season',
    name: '流感季节',
    description: '流感高发期，急诊和儿科压力大',
    timeOfDay: 'afternoon',
    isWeekend: false,
    specialEvents: ['流感疫情', '呼吸道感染高发'],
    dataModifiers: {
      patientFlowMultiplier: 1.8,
      alertSeverityIncrease: true,
      equipmentIssues: false,
      crowdingAreas: ['急诊科', '儿科', '发热门诊']
    }
  },
  {
    id: 'emergency_drill',
    name: '应急演练',
    description: '医院应急疏散演练，模拟紧急情况',
    timeOfDay: 'afternoon',
    isWeekend: false,
    specialEvents: ['消防演练', '紧急疏散', '应急响应测试'],
    dataModifiers: {
      patientFlowMultiplier: 1.2,
      alertSeverityIncrease: true,
      equipmentIssues: false,
      crowdingAreas: ['所有安全出口', '电梯区域']
    }
  }
]

// 根据场景生成特定的数据
export const generateScenarioData = (scenarioId: string) => {
  const scenario = demoScenarios.find(s => s.id === scenarioId)
  if (!scenario) {
    return realDataService.getAllRealTimeData()
  }

  // 获取基础数据
  const baseData = realDataService.getAllRealTimeData()
  
  // 根据场景修改数据
  const modifiedData = {
    ...baseData,
    scenario: scenario,
    timestamp: new Date(),
  }

  // 修改患者流量
  modifiedData.patientFlow = modifiedData.patientFlow.map((item: any) => ({
    ...item,
    patients: Math.round(item.patients * scenario.dataModifiers.patientFlowMultiplier),
    emergency: Math.round(item.emergency * scenario.dataModifiers.patientFlowMultiplier * 1.2),
    outpatient: Math.round(item.outpatient * scenario.dataModifiers.patientFlowMultiplier),
  }))

  // 修改KPI指标
  if (scenario.dataModifiers.patientFlowMultiplier > 1.2) {
    modifiedData.kpis.averageWaitTime.value *= 1.5
    modifiedData.kpis.bedUtilization.value = Math.min(100, modifiedData.kpis.bedUtilization.value * 1.1)
  }

  // 添加场景特定的告警
  if (scenario.dataModifiers.alertSeverityIncrease) {
    const scenarioAlerts = generateScenarioAlerts(scenario)
    modifiedData.alerts = [...modifiedData.alerts, ...scenarioAlerts]
  }

  // 修改科室数据
  modifiedData.departments = modifiedData.departments.map((dept: any) => {
    const isCrowded = scenario.dataModifiers.crowdingAreas.includes(dept.name)
    return {
      ...dept,
      currentPatients: isCrowded 
        ? Math.min(dept.capacity, Math.round(dept.currentPatients * 1.4))
        : Math.round(dept.currentPatients * scenario.dataModifiers.patientFlowMultiplier),
      waitingTime: isCrowded ? dept.waitingTime * 2 : dept.waitingTime,
      utilizationRate: isCrowded 
        ? Math.min(100, dept.utilizationRate * 1.2)
        : Math.round(dept.utilizationRate * scenario.dataModifiers.patientFlowMultiplier)
    }
  })

  // 修改设备数据
  if (scenario.dataModifiers.equipmentIssues) {
    modifiedData.equipment = modifiedData.equipment.map((device: any, index: number) => {
      // 随机选择一些设备进入维护状态
      if (index % 4 === 0) {
        return {
          ...device,
          status: 'maintenance',
          currentUtilization: 0
        }
      }
      return device
    })
  }

  return modifiedData
}

// 生成场景特定的告警
const generateScenarioAlerts = (scenario: DemoScenario) => {
  const alerts = []
  const now = new Date()

  if (scenario.specialEvents?.includes('流感疫情')) {
    alerts.push({
      id: `SCENARIO-${Date.now()}-1`,
      type: 'epidemic',
      severity: 'high',
      title: '流感患者激增告警',
      location: '发热门诊',
      description: '流感患者数量比平时增加200%，需要加强防护措施',
      timestamp: new Date(now.getTime() - 10 * 60 * 1000).toISOString(),
      status: 'active',
      assignee: '感染科主任',
      estimatedResolution: '流感季结束',
      impact: '可能引起院内感染，需严格隔离措施'
    })
  }

  if (scenario.specialEvents?.includes('应急响应测试')) {
    alerts.push({
      id: `SCENARIO-${Date.now()}-2`,
      type: 'drill',
      severity: 'medium',
      title: '应急演练进行中',
      location: '全院',
      description: '正在进行消防疏散演练，请配合演练工作',
      timestamp: now.toISOString(),
      status: 'active',
      assignee: '安全保卫科',
      estimatedResolution: '1小时',
      impact: '正常诊疗秩序暂时受影响'
    })
  }

  if (scenario.dataModifiers.crowdingAreas.length > 2) {
    alerts.push({
      id: `SCENARIO-${Date.now()}-3`,
      type: 'crowding',
      severity: 'high',
      title: '多区域拥挤告警',
      location: scenario.dataModifiers.crowdingAreas.join('、'),
      description: `${scenario.dataModifiers.crowdingAreas.join('、')}等区域出现拥挤，需要疏散引导`,
      timestamp: new Date(now.getTime() - 5 * 60 * 1000).toISOString(),
      status: 'active',
      assignee: '值班护士长',
      estimatedResolution: '30分钟',
      impact: '患者等待时间延长，满意度下降'
    })
  }

  return alerts
}

// 时间段数据变化模拟
export const getTimeBasedData = () => {
  const hour = new Date().getHours()
  
  if (hour >= 7 && hour <= 10) {
    return generateScenarioData('morning_rush')
  } else if (hour >= 14 && hour <= 17) {
    return generateScenarioData('afternoon_normal')
  } else if (hour >= 19 && hour <= 22) {
    return generateScenarioData('evening_emergency')
  } else {
    return generateScenarioData('night_quiet')
  }
}

// 演示控制器
export const demoController = {
  currentScenario: 'afternoon_normal',
  
  setScenario: (scenarioId: string) => {
    demoController.currentScenario = scenarioId
  },
  
  getData: () => {
    return generateScenarioData(demoController.currentScenario)
  },
  
  getAvailableScenarios: () => {
    return demoScenarios
  },
  
  startAutoDemo: (callback: (data: any) => void, interval: number = 60000) => {
    let currentIndex = 0
    
    const updateScenario = () => {
      const scenario = demoScenarios[currentIndex]
      demoController.setScenario(scenario.id)
      const data = demoController.getData()
      callback(data)
      
      currentIndex = (currentIndex + 1) % demoScenarios.length
    }
    
    // 立即执行一次
    updateScenario()
    
    // 定期切换场景
    const intervalId = setInterval(updateScenario, interval)
    
    return () => clearInterval(intervalId)
  }
}

export default demoController